<template>
  <div class="detail">
    <van-nav-bar ref="navbar" fixed left-arrow :border="false" @click-left="handleBack">
      <template slot="right">
        <van-icon v-login="handleFavorites" :name="isFavorites ? 'like' : 'like-o'"></van-icon>
      </template>
    </van-nav-bar>
    <div class="img-list">
      <van-swipe class="my-swipe" :autoplay="3000"  indicator-color="white">
        <van-swipe-item v-for="(item, index) in detail.imgs" :key="index">
          <img class="swipe-img" :src="domain + item" alt="" />
          <div class="preview">
            <van-icon name="photo" size="24" @click="handlePreview(index)"></van-icon>
          </div>
        </van-swipe-item>
      </van-swipe>
      
    </div>
    <div class="info">
      <div class="time">{{ detail.activeTime }}</div>
      <div class="name mt10">{{ detail.name }}</div>
      <div class="price mt10">{{ detail.price | num2Money }} KZ</div>
      <div class="tags mt10">
        <van-tag v-for="(param, index) in paramList" :key="index" class="mr15 mb15" size="large" plain color="#666">{{ param.portugalName + ":" + param.portugalNameInner }}</van-tag>
      </div>
      <div class="desc">
        <div class="panel-title">Description</div>
        <div class="content" v-html="detail.des"></div>
      </div>
      <div class="user flex">
        <div class="flex-auto width0">
          <div class="name">{{ detail.creatorNick }}</div>
          <div class="status">{{ detail.createTime }}</div>
        </div>
        <div class="head flex-none">
          <img v-if="detail.portrait&&detail.portrait.startsWith('http')" :src="detail.portrait" alt="" />
          <img v-else :src="domain + detail.portrait" alt="" />
        </div>
      </div>
      <div class="user-ad">Todos os anúncios deste anunciante</div>
      <div class="location flex mt10">
        <div class="flex-none">
          <van-icon name="location"></van-icon>
        </div>
        <div class="flex-auto width0 address">{{ detail.areaName }}</div>
        <!-- <div class="flex-none">
          <div class="map"></div>
        </div> -->
      </div>
      <div class="recommend">
        <div class="panel-title mv15">Anúncios relacionados</div>
        <GoodsRecommend :category-id="detail.categoryId" @handleDetail='handleDetail'/>
      </div>
      <div class="footer">
        <!-- <van-collapse v-model="activeNames" :border="false">
          <van-collapse-item title="CATEGORY" name="1">
            <ul class="cate-list">
              <li>cate1</li>
              <li>cate1</li>
              <li>cate1</li>
              <li>cate1</li>
              <li>cate1</li>
              <li>cate1</li>
              <li>cate1</li>
            </ul>
          </van-collapse-item>
        </van-collapse> -->
        <div class="num flex flex-align-items flex-justify-content-between">
          <div>Views:{{ detail.views }}</div>
          <div v-if="detail.id">ID:{{ detail.id.toString().substr(0,6)}}</div>
         
          <div class="ad" @click="adVisible = true" style="display:flex;align-items: center;">
            <img style="width: 15px; height: 15px;margin-right:3px" :src="require('@/assets/images/warning.png')" alt="" />
            <span>Denunciar anúncio</span>
          </div>
           <div @click="shareFacebook" style="display:flex;align-items: center;">
             <img style="width: 20px; height: 20px;" :src="require('@/assets/images/share.png')" alt="" />
             <!-- <van-icon size="24px" name="share-o" color="#fb8c24"/> -->
         </div>
          <!-- <van-icon name="share-o" @click="shareFacebook" color="#fb8c24"/> -->
        </div>
      </div>
    </div>
    <div class="fixed-btn">
      <div class="flex-1 mr5">
        <van-button block plain color="#333" @click="handleShowPhone">{{ showPhone ? detail.telephone : "Ver número" }}</van-button>
      </div>
      <div class="flex-1 ml5">
        <van-button block color="#fb8c24" @click="toChat">Message</van-button>
      </div>
    </div>

    <!-- 对话框 -->
    <van-overlay :show="show" @click="show = false" v-if="hasLogin">
      <div class="wrapper" @click.stop>
         <ChatDetail :supplyId="id" :fromGoods="true" @cancel='cancel'></ChatDetail>
      </div>
    </van-overlay>
    <!-- 举报 -->
    <van-overlay :show="adVisible" @click="adVisible = false" v-if="hasLogin">
      <div class="wrapper" @click.stop>
        <van-nav-bar
          
          left-text="cancel"
          left-arrow
          @click-left="adVisible = false"
        />
         <van-form @submit="submitComplain">
           <van-field name="radio">
            <template #input>
              <van-radio-group v-model="ruleForm.resource">
                <van-radio checked-color="#fb8c24" v-for="(item,index) in complainList" :key="index" :name="item" style="margin-bottom:10px">{{item}}</van-radio>
              </van-radio-group>
            </template>
          </van-field>
           
          <van-field
            v-model="ruleForm.desc"
            label="Mensagem"
            required
            type="textarea"
            :rows="4"
            :rules="[{ required: true, message: '' }]"
          />
          <div style="margin: 16px;">
            <van-button round block type="primary" style="background-color: rgb(251, 140, 36);border:none" native-type="submit">Confirmar</van-button>
          </div>
        </van-form>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import GoodsRecommend from "@/components/goods-recommend";
import Api from "@/api";
import { Domain, MAPKEY } from "@/constants";
import { isLogin } from "@/utils";
// import { Loader } from "@googlemaps/js-api-loader";
import ChatDetail from "@/components/chat/ChatDetail"
export default {
  name: "Detail",
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component,
    GoodsRecommend,
    ChatDetail
  },
  data() {
    return {
      activeNames: [],
      domain: Domain,
      id: "",
      detail: {},
      showImg: "",
      showPhone: false,
      carouselIndex: 0,
      isFavorites: false,
      map: null,
      sharing: {},
      paramList: [],
      show:false,
      user:{},
      hasLogin: false,
      scaleImgs:[],
      adVisible:false,
      ruleForm: {},
       // 投诉类型
      complainList: ["Burla", "Duplicado", "Ofensiva", "Categoria Incorrecta", "Itens Proibidos", "Anúncio desactualizado", "Outro"],
    };
  },
  watch:{
    $route(to,from){
      this.loadDetail()
      this.$router.go(0);
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.hasLogin = isLogin();
    this.loadDetail();
    // this.initMap();
    this.getPosition();
    this.loadTree();
  },
  mounted() {
    document.addEventListener("scroll", (event) => {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 50) {
        document.querySelector(".van-nav-bar").style.backgroundColor = "#fff";
      } else {
        document.querySelector(".van-nav-bar").style.backgroundColor = "transparent";
      }
    });
  },
  methods: {
    // 获取用户判断  当前用户不能给自己发消息
     loadUserInfo() {
      Api.loadUser().then((res) => {
        this.user = res
        if(this.user.username === this.detail.username){
          this.$toast.fail('Não há necessidade de deixar recado para seus próprios produtos')
        }else{
          this.show = true
        }
      });
    },
    loadDetail() {
      this.scaleImgs = []
      const params = { id: this.id };
      Api.goodsDetail(params).then((res) => {
        this.detail = res;
        this.sharing.url = window.location.href;
        this.sharing.title = this.detail.name;
        this.sharing.description = this.detail.des;
        this.sharing.quote = "This is Vivebo";
        if (this.detail.parameterList) {
          this.paramList = JSON.parse(this.detail.parameterList);
        }
        this.detail.imgs = res.imgList ? JSON.parse(res.imgList) : [];
        if(this.detail.imgs.length!==0){
          this.detail.imgs.forEach((item)=>{
            this.scaleImgs.push(this.domain + item)
          })
        }
        this.showImg = this.detail.imgs.length > 0 ? this.detail.imgs[0] : "";
        this.loadFavoritesStatus();
        // this.initMap();
      });
    },
    loadTree() {
      Api.areaTree().then((res) => {
        this.multiOptions = res;
      });
    },
    loadFavoritesStatus() {
      Api.queryFavorites({ commodityId: this.id }).then((res) => {
        this.isFavorites = res;
      });
    },
    handleFavorites() {
      const params = {
        commodityId: this.id,
      };
      Api.addFavorites(params).then(() => {
        this.loadFavoritesStatus();
      });
    },
    handleShowPhone() {
      this.showPhone = !this.showPhone;
    },
    shareFacebook() {
      let metaArr = [
          'og:url', "https://www.vivebo.com/vivebo/sharding/new/"+this.detail.id,
        'og:title', this.sharing.title,
        'og:description', this.sharing.description,
        'og:image', this.sharing.image,
        'og:type', 'website'
      ]
      let metaParams = metaArr.toString()
      window.FB.ui({
        method: 'share',
        href: `https://www.vivebo.com/vivebo/share/new/`+this.detail.id
      }, function(response){
        //分享回调，可留空
      })
      // window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(`https://www.vivebo.com/vivebo/share/new?meta=${metaParams}`))
    },
    handleBack() {
      this.$router.back();
    },
    handlePreview(index) {
      ImagePreview({
        images: this.scaleImgs,
        closeable: true,
        startPosition: index,
      });
    },
    getPosition() {
      return new Promise((resolve) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const { latitude, longitude } = position.coords;
              resolve({
                lat: latitude,
                lng: longitude,
              });
            },
            () => {
              resolve({
                lat: 0,
                lng: 0,
              });
            }
          );
        } else {
          resolve({
            lat: 0,
            lng: 0,
          });
        }
      });
    },
    // initMap() {
    //   const mapLoader = new Loader({
    //     apiKey: MAPKEY,
    //     version: "weekly",
    //   });
    //   mapLoader.load().then(() => {
    //     const position = { lat: this.detail.latitude, lng: this.detail.longitude };
    //     this.map = new window.google.maps.Map(this.$refs.googleMap, {
    //       center: position,
    //       zoom: 8,
    //     });
    //     new window.google.maps.Marker({
    //       position: position,
    //       map: this.map,
    //     });
    //   });
    // },
   toChat(){
      if (!isLogin()) {
        this.$router.push("/login");
      } else {
        this.loadUserInfo()
      }
      // this.$router.push({path:"chatDetail",query:{supplyId:this.id}})
    },
    handleDetail(item) {
      this.$router.push({
        path: "/detail",
        query: {
          id: item.id,
        },
      });
    },
    cancel(val){
      this.show = val
    },
    // 投诉
    submitComplain(){
      let params = {};
      params.commodityId = this.detail.id;
      params.reason = JSON.stringify(this.ruleForm);
      console.log(params);
      Api.complainGoods(params).then((res) => {
        this.ruleForm = { desc: "", resource: "" };
      });
      this.adVisible = false;
    }
  },
};
</script>
<style lang="less" scoped>
.detail {
  background-color: #fff;
  padding-bottom: 60px;
  position: relative;
  .van-nav-bar {
    background-color: transparent;
  }
  .img-list {
    position: relative;
    .my-swipe {
      width: 100%;
      height: calc(100vw * 0.6);
      overflow: hidden;
      
      .van-swipe-item{
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .swipe-img {
        // width: 100%;
        height: 100%;
        // object-fit: cover;
      }
    }
    .preview {
      position: absolute;
      bottom: 10px;
      right: 10px;
    }
  }
  .info {
    padding: 15px;
    box-sizing: border-box;
    .panel-title {
      color: #000;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
    }
    .time {
      color: #666;
      font-size: 14px;
    }
    .name {
      color: #333;
      font-size: 18px;
      font-weight: bold;
      text-overflow: ellipsis;
      overflow: hidden;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
    }
    .price {
      color: #333;
      font-size: 20px;
      font-weight: bold;
    }
    .desc {
      border-top: 1px solid #ededed;
      border-bottom: 1px solid #ededed;
      padding: 15px 0;
      box-sizing: border-box;
      .content {
        color: #666;
        font-size: 15px;
      }
    }
    .user {
      padding: 15px 0;
      .name {
        font-weight: bold;
        font-size: 16px;
        color: #000;
      }
      .status {
        font-size: 12px;
        color: #989898;
      }
      .head {
        width: 60px;
        height: 60px;
        img {
          width: 100%;
          height: 100%;
          border-radius: 100%;
          background-color: #ddd;
          display: inline-block;
        }
      }
    }
    .user-ad {
      font-size: 14px;
      color: #000;
      font-weight: bold;
    }
    .location {
      .address {
        color: #000;
        font-size: 16px;
        font-weight: bold;
        margin: 0 10px;
        word-break: break-all;
      }
      .map {
        width: 145px;
        height: 105px;
        border-radius: 8px;
        background-color: #f2f2f2;
      }
    }
    .footer {
      /deep/ .cate-list {
        li {
          padding: 5px 0;
          text-decoration: underline;
        }
      }
      .num {
        height: 50px;
        line-height: 50px;
        color: #666;
        div {
          &:last-child {
            font-weight: bold;
          }
        }
      }
    }
  }
  .fixed-btn {
    height: 60px;
    display: flex;
    border-top: 1px solid #ededed;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    align-items: center;
    background-color: #fff;
    padding: 0 10px;
    box-sizing: border-box;
  }
}
// ::v-deep.van-popup--bottom.van-popup--round{
//   border-radius: 0;
// }
// ::v-deep.van-action-sheet{
//   height: 100vh;
// }
.van-overlay{
  height: 100%;
  background-color: #fff;
  ::v-deep .van-nav-bar__text{
    color: #333;
    font-size: 16px;
  }
}
</style>
